package cn.doitedu.tags_query.service;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.springframework.stereotype.Service;


@Service
public class UserTagServiceImpl implements UserTagService {

    Table t_profile = null;
    Table t_index = null;

    /**
     * 利用构造函数构造hbase客户端连接
     */
    public UserTagServiceImpl() {
        try {
            Configuration conf = HBaseConfiguration.create();
            conf.set("hbase.zookeeper.quorum", "spark01:2181,spark02:2181,spark03:2181");

            Connection conn = ConnectionFactory.createConnection(conf);

            t_profile = conn.getTable(TableName.valueOf("userprofile"));
            t_index = conn.getTable(TableName.valueOf("ids_index"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据 gid查询画像
     * @param gid
     * @return
     */
    @Override
    public String getTagsByGid(String gid) {

        String tags = "status:404";

        try {
            Get get = new Get(gid.getBytes());
            Result result = t_profile.get(get);
            byte[] value = result.getValue("f".getBytes(), "tags".getBytes());
            tags = new String(value);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return tags;
    }


    /**
     * 根据任意id标识查询画像
     * @param id
     * @return
     */
    @Override
    public String getTagsById(String id) {
        String tags = "status:404";

        try {
            // 先根据id查询索引表得到gid
            Get get = new Get(id.getBytes());
            Result result = t_index.get(get);
            byte[] gid = result.getValue("f".getBytes(), "g".getBytes());

            // 再根据gid去画像表查询标签数据
            tags = getTagsByGid(new String(gid));


        } catch (Exception e) {
            e.printStackTrace();
        }


        return tags;
    }
}
